/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.rational.sheet.table.cell.model;

/**
 *
 * @author Overmind
 */
public class CellAddress
{
    private int row;
    private int column;
    
    public CellAddress(int row, int column)
    {
        this.row = row;
        this.column = column;
    }

    public static String getColumnName(int column)
    {
        StringBuilder builder = new StringBuilder();

        while (column >= 0)
        {
            builder.append((char)('a' + (column % 26)));
            column = (column / 26) - 1;
        }

        return builder.reverse().toString();
    }
    
    public static String getRowName(int row)
    {
        return Integer.toString(row + 1);
    }
    
    @Override
    public String toString()
    {
        return getRowName(row) + getColumnName(column);
    }
    
    public static int getColumnByName(String name) throws NumberFormatException
    {
        if(!name.isEmpty())
        {
            int result = 0;

            for (int i = 0; i < name.length(); ++i)
            {
                char ch = name.charAt(i);

                if(ch >= 'a' && ch <= 'z')
                {
                    result *= 26;
                    result += (ch - 'a');
                }
                else
                {
                    throw new NumberFormatException();
                }
            }

            return result;
        }
        else
        {
            throw new NumberFormatException();
        }
    }
    
    public static int getRowByName(String name) throws NumberFormatException
    {
        return Integer.parseInt(name) - 1;
    }
    
    public static CellAddress parseCellAddress(String address) throws NumberFormatException
    {        
        int columnShift = -1;
        
        for(int i=0;i<address.length();++i)
        {
            char ch = address.charAt(i);
            
            if(ch >= '0' && ch <= '9')
            {
                columnShift = i;
                break;
            }
        }
        
        if(columnShift == -1)
        {
            throw new NumberFormatException();
        }
        
        String columnString = address.substring(0, columnShift);
        String rowString = address.substring(columnShift);
        
        int column = getColumnByName(columnString);
        int row = getRowByName(rowString);
        
        return new CellAddress(row, column);
    }
    
    public int getRow()
    {
        return row;
    }
    
    public int getColumn()
    {
        return column;
    }
}
